'use strict';

const Controller = require('./base');

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const res = ctx.state.user
    
    ctx.helper.success(ctx, res);
  }

  async info() {
    const { ctx } = this;
    ctx.body = `Value from session: ${ctx.session.abc}`;
  }

  // 登录
  async register() {
    const { ctx, app, service } = this;
    const { code } = ctx.request.query; 

    // 获取 sessionKey
    let res = await service.weapp.getSessionKey(code);
    const user = await service.user.create(res);
    
    res = {
        token: await service.actionToken.apply(user._id, user.openid),
        userinfo: user.userinfo ? user.userinfo : false,
    };

    ctx.helper.success(ctx, res);
  }

  // 更新用户数据
  async update() {
    const { ctx, service, } = this;
    const { encryptedData, iv, userInfo } = ctx.request.query; 
    const userinfo = JSON.parse(userInfo);

    const descData = await service.weapp.authorization(encryptedData, iv);
    const payload = {
        unionId: descData.unionId,
        userinfo: userinfo ,
    };
    const _id = ctx.state.user.data._id;
    payload.userinfo.expirationTime = new Date().getTime() + 864000000; // 240个小时 10天 用户信息在十天之后过期
    let res = await service.user.updateById(payload, _id);
    res = payload.userinfo;
    ctx.helper.success(ctx, res);
  }
}

module.exports = UserController;
